package org.jeecg.modules.fep.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.modules.fep.entity.FepOrders;
import org.jeecg.modules.fep.entity.FepInstallments;
import org.jeecg.modules.fep.entity.FepOrdersProduct;
import org.jeecg.modules.fep.mapper.FepInstallmentsMapper;
import org.jeecg.modules.fep.mapper.FepOrdersProductMapper;
import org.jeecg.modules.fep.mapper.FepOrdersMapper;
import org.jeecg.modules.fep.service.IFepOrdersService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 订单模块
 * @Author: jeecg-boot
 * @Date:   2023-04-14
 * @Version: V1.0
 */
@Service
public class FepOrdersServiceImpl extends ServiceImpl<FepOrdersMapper, FepOrders> implements IFepOrdersService {

	@Autowired
	private FepOrdersMapper fepOrdersMapper;
	@Autowired
	private FepInstallmentsMapper fepInstallmentsMapper;
	@Autowired
	private FepOrdersProductMapper fepOrdersProductMapper;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(FepOrders fepOrders, List<FepInstallments> fepInstallmentsList, List<FepOrdersProduct> fepOrdersProductList) {

         fepOrders.setShouldPayTotalPrice(0.00);
		fepOrdersMapper.insert(fepOrders);

		if(fepInstallmentsList!=null && fepInstallmentsList.size()>0) {
			for(FepInstallments entity:fepInstallmentsList) {
				//外键设置
				entity.setOrderNo(fepOrders.getOrderNo());
				fepInstallmentsMapper.insert(entity);
			}
		}

		if(fepOrdersProductList!=null && fepOrdersProductList.size()>0) {
			for(FepOrdersProduct entity:fepOrdersProductList) {
				//外键设置
				entity.setOrderNo(fepOrders.getOrderNo());

				// 计算单品总价
				Integer quantity = entity.getQuantity();
				Double unitPrice = entity.getUnitPrice();
				BigDecimal bdq = new BigDecimal(Integer.toString(quantity));
				BigDecimal bdu= new BigDecimal(Double.toString(unitPrice));
				entity.setTotalPrice( bdq.multiply(bdu).doubleValue());

				// * 关联更新主表应付总价字段
				Double shouldPayTotalPrice = fepOrders.getShouldPayTotalPrice();
				BigDecimal bigDecimalShould= new BigDecimal(Double.toString(shouldPayTotalPrice));
				Double totalPrice = entity.getTotalPrice();
				BigDecimal bigDecimalTotalPrice= new BigDecimal(Double.toString(totalPrice));
				BigDecimal add = bigDecimalShould.add(bigDecimalTotalPrice);
				// 2、定义查询条件
				QueryWrapper<FepOrders> queryOnes = new QueryWrapper<>();
				queryOnes.lambda().eq(FepOrders::getOrderNo,fepOrders.getOrderNo());
				fepOrdersMapper.selectOne(queryOnes);
				// 3、设置条件和要更新的字段
				FepOrders orderss = new FepOrders();
				orderss.setId(fepOrders.getId());
				orderss.setShouldPayTotalPrice(add.doubleValue());
				// 4、更新指定字段
				fepOrders.setShouldPayTotalPrice(add.doubleValue());
				fepOrdersMapper.updateById(orderss);


				fepOrdersProductMapper.insert(entity);
				// * 关联更新主表品种数
				//  1、count出当前订单号水果中
				QueryWrapper<FepOrdersProduct> query = new QueryWrapper<>();
				query.select("distinct product_id").lambda().eq(FepOrdersProduct::getOrderNo,entity.getOrderNo());
				Long num = fepOrdersProductMapper.selectCount(query);
			//	System.out.println("num+------------->"+num);

				// 2、定义查询条件
				QueryWrapper<FepOrders> queryOne = new QueryWrapper<>();
				queryOne.lambda().eq(FepOrders::getOrderNo,fepOrders.getOrderNo());
				fepOrdersMapper.selectOne(queryOne);
				// 3、设置条件和要更新的字段
				FepOrders orders = new FepOrders();
				orders.setId(fepOrders.getId());
				orders.setQuantity(Math.toIntExact(num));
				// 4、更新指定字段
				fepOrdersMapper.updateById(orders);

			}
		}




	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(FepOrders fepOrders,List<FepInstallments> fepInstallmentsList,List<FepOrdersProduct> fepOrdersProductList) {

		//1.先删除子表数据
		fepInstallmentsMapper.deleteByOrderNo(fepOrders.getOrderNo());
		fepOrdersProductMapper.deleteByOrderNo(fepOrders.getOrderNo());
		//2.子表数据重新插入
		// 1、清空已经支付信息
		fepOrders.setPaidAmount(null);
		// 清空主表应付
		fepOrders.setShouldPayTotalPrice(0.00);
		if(fepInstallmentsList!=null && fepInstallmentsList.size()>0) {
			for(FepInstallments entity:fepInstallmentsList) {
				//外键设置
				entity.setOrderNo(fepOrders.getOrderNo());
				// ** 关联更新主表已支付信息
				// 2、累计支付金额计算
				if (fepOrders.getPaidAmount()==null){
					Double amount = entity.getAmount();
					fepOrders.setPaidAmount(amount);
				}else {
					Double paidAmount = fepOrders.getPaidAmount();
					//将double转为BigDecimal再相加计算
					BigDecimal bigDecimalPaid = new BigDecimal(Double.toString(paidAmount));
					Double amount = entity.getAmount();
					BigDecimal bigDecimalAmount= new BigDecimal(Double.toString(amount));
					BigDecimal add = bigDecimalPaid.add(bigDecimalAmount);
					// 3、更新计算结果到主表已支付字段
					fepOrders.setPaidAmount(add.doubleValue());
				}
				// ** 关联更新主表未支付信息
				// 1、获取总金额
				Double payTotalPrice = fepOrders.getPayTotalPrice();
				BigDecimal bigDecimalTotal = new BigDecimal(Double.toString(payTotalPrice));
				// 2、获取已支付金额
				Double paidAmount = fepOrders.getPaidAmount();
				BigDecimal bigDecimalPaid = new BigDecimal(Double.toString(paidAmount));
				// 3、计算出未支付金额更新到主表
				BigDecimal absAmount = bigDecimalTotal.subtract(bigDecimalPaid);
				fepOrders.setUpaidAmount(absAmount.doubleValue());

				// ** 关联更新主表是否结清  o-结清 1-未结清
				 // 1、获取已支付金额
				Double paidAmount1 = fepOrders.getPaidAmount();
				// 2、获取总价金额
				Double payTotalPrice1 = fepOrders.getPayTotalPrice();
				// 3、比较两者是否相等，相等为结清，不相等为未结清
				if (Double.doubleToLongBits(paidAmount1)==Double.doubleToLongBits(payTotalPrice1)){
					fepOrders.setIsSettle(0);

				}else {
					fepOrders.setIsSettle(1);

				}

				fepInstallmentsMapper.insert(entity);
			}
		}
		if(fepOrdersProductList!=null && fepOrdersProductList.size()>0) {
			for(FepOrdersProduct entity:fepOrdersProductList) {
				//外键设置
				entity.setOrderNo(fepOrders.getOrderNo());


				//* 更新总价
				Integer quantity = entity.getQuantity();
				Double unitPrice = entity.getUnitPrice();
				BigDecimal bdq = new BigDecimal(Integer.toString(quantity));
				BigDecimal bdu= new BigDecimal(Double.toString(unitPrice));
				entity.setTotalPrice(bdq.multiply(bdu).doubleValue());
				fepOrdersProductMapper.insert(entity);

				// * 关联更新主表品种数
				//  1、count出当前订单号水果中
				QueryWrapper<FepOrdersProduct> query = new QueryWrapper<>();
				query.select("distinct product_id").lambda().eq(FepOrdersProduct::getOrderNo,entity.getOrderNo());
				Long num = fepOrdersProductMapper.selectCount(query);
				System.out.println("num+------------->"+num);

				//  2、更新到主表
				fepOrders.setQuantity(Math.toIntExact(num));

				//   * 关联更新主表应付总价字段
                // 1、获取当前应付总价
				Double shouldPayTotalPrice = fepOrders.getShouldPayTotalPrice();
				BigDecimal bigDecimalShould= new BigDecimal(Double.toString(shouldPayTotalPrice));

				Double totalPrice = entity.getTotalPrice();
				BigDecimal bigDecimalTotalPrice= new BigDecimal(Double.toString(totalPrice));
				BigDecimal add = bigDecimalShould.add(bigDecimalTotalPrice);
				fepOrders.setShouldPayTotalPrice(add.doubleValue());

			}
		}

		fepOrdersMapper.updateById(fepOrders);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		// 根据id查出对应的orderNo
		FepOrders orders = fepOrdersMapper.selectById(id);

		fepInstallmentsMapper.deleteByOrderNo(orders.getOrderNo());
		fepOrdersProductMapper.deleteByOrderNo(orders.getOrderNo());
		fepOrdersMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			// 根据id查出对应的orderNo
			FepOrders orders = fepOrdersMapper.selectById(id);
			String orderNo = orders.getOrderNo();
			fepInstallmentsMapper.deleteByOrderNo(orderNo.toString());
			fepOrdersProductMapper.deleteByOrderNo(orderNo.toString());
			fepOrdersMapper.deleteById(id);
		}
	}

	@Override
	public List<FepOrders> selectTopProductsSales(String dates) {
		List<FepOrders> fepOrdersList = fepOrdersMapper.selectTopProductsSales(dates);
		return fepOrdersList;
	}

	@Override
	public List<FepOrders> selectTopUpaidTotal() {
		List<FepOrders> fepOrdersList = fepOrdersMapper.selectTopUpaidTotal();
		return fepOrdersList;
	}

}
